package io.github.eric.urpc.standalone.client;

import io.github.eric.urpc.client.Client;
import io.github.eric.urpc.client.ClientConfig;
import io.github.eric.urpc.core.util.RandomStringGenerator;
import io.github.eric.urpc.standalone.common.msg.UserLogin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.UUID;

public class MobileDevice {
    private static final Logger LOGGER = LoggerFactory.getLogger(MobileDevice.class);
    private String userId;
    private String userName;
    private Client client;
    private ChatManager chatManager;
    private FriendManager friendManager;

    public MobileDevice() {
        ClientConnListener clientConnListener = new ClientConnListener();
        ClientRpcController clientRpcController = new ClientRpcController();
        String host = System.getProperty("host", "127.0.0.1");
        // init config
        ClientConfig clientConfig = new ClientConfig.Builder()
//                .nettyLoggingLevel(LogLevel.INFO)
                .applicationName("mobile-device")
                .serverHost(host)
                .serverPort(52379)
                .heartBeatInterval(5)
                .rpcExecutorThreadSize(1)
                .connectionListeners(Collections.singletonList(clientConnListener))
                // set controllers
                .rpcControllers(Collections.singletonList(clientRpcController))
                .build();

        // init client and connect to server
        client = new Client(clientConfig);

        String applicationName = client.getClientConfig().getApplicationName();
        String applicationId = UUID.randomUUID().toString();
        userId = "User-" + applicationId;
        userName = RandomStringGenerator.genRandomString(4);

        clientConnListener.setUserId(userId);
        clientConnListener.setUserName(userName);
        clientRpcController.setUserId(userId);
        clientRpcController.setUserName(userName);
        clientRpcController.setClient(client);
        clientRpcController.setMobileDevice(this);

        start();
    }

    public void start() {
        UserLogin userLogin = new UserLogin();
        userLogin.setUserId(userId);
        userLogin.setUserName(userName);
        client.sendAsync(userLogin);

        LOGGER.info("我的UserId是{}, userName是{}", userLogin.getUserId(), userLogin.getUserName());

        friendManager = new FriendManager(client);
        chatManager = new ChatManager(client, this, userId, userName);
//        sendMessageManually();
    }

    public ChatManager getChatManager() {
        return chatManager;
    }

    public FriendManager getFriendManager() {
        return friendManager;
    }
}
